import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useStockStore = defineStore('stock', () => {
  const STORAGE_KEY = 'erppos_stock'
  const HISTORY_KEY = 'erppos_stock_history'
  // 库存数据
  const stockList = ref([])
  
  // 库存操作历史
  const stockHistory = ref([])
  
  // 初始化示例数据
  const initializeStock = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    const cachedHistory = localStorage.getItem(HISTORY_KEY)
    if (cached) stockList.value = JSON.parse(cached)
    if (cachedHistory) stockHistory.value = JSON.parse(cachedHistory)
    if (cached) return
    stockList.value = [
      {
        id: 'P001',
        code: 'SKU001',
        name: '可口可乐',
        category: '饮料',
        specification: '330ml',
        unit: '瓶',
        quantity: 150,
        minStock: 20,
        maxStock: 500,
        costPrice: 2.50,
        salePrice: 3.50,
        warehouse: '主仓库',
        lastUpdated: new Date('2024-01-15').toISOString(),
        supplier: '可口可乐公司'
      },
      {
        id: 'P002',
        code: 'SKU002',
        name: '康师傅方便面',
        category: '食品',
        specification: '袋装',
        unit: '袋',
        quantity: 8,
        minStock: 10,
        maxStock: 200,
        costPrice: 3.20,
        salePrice: 4.50,
        warehouse: '主仓库',
        lastUpdated: new Date('2024-01-14').toISOString(),
        supplier: '康师傅食品'
      },
      {
        id: 'P003',
        code: 'SKU003',
        name: '洗衣粉',
        category: '日用品',
        specification: '1kg',
        unit: '袋',
        quantity: 0,
        minStock: 5,
        maxStock: 100,
        costPrice: 12.00,
        salePrice: 18.00,
        warehouse: '分仓库A',
        lastUpdated: new Date('2024-01-13').toISOString(),
        supplier: '清洁用品公司'
      },
      {
        id: 'P004',
        code: 'SKU004',
        name: 'iPhone手机壳',
        category: '电子产品',
        specification: 'iPhone 15',
        unit: '个',
        quantity: 45,
        minStock: 10,
        maxStock: 200,
        costPrice: 25.00,
        salePrice: 58.00,
        warehouse: '主仓库',
        lastUpdated: new Date('2024-01-16').toISOString(),
        supplier: '手机配件厂'
      },
      {
        id: 'P005',
        code: 'SKU005',
        name: '牛仔裤',
        category: '服装',
        specification: 'L码',
        unit: '件',
        quantity: 25,
        minStock: 5,
        maxStock: 50,
        costPrice: 80.00,
        salePrice: 158.00,
        warehouse: '分仓库B',
        lastUpdated: new Date('2024-01-12').toISOString(),
        supplier: '服装制造商'
      },
      {
        id: 'P006',
        code: 'SKU006',
        name: '矿泉水',
        category: '饮料',
        specification: '500ml',
        unit: '瓶',
        quantity: 200,
        minStock: 50,
        maxStock: 1000,
        costPrice: 1.20,
        salePrice: 2.00,
        warehouse: '主仓库',
        lastUpdated: new Date('2024-01-17').toISOString(),
        supplier: '饮用水公司'
      },
      {
        id: 'P007',
        code: 'SKU007',
        name: '薯片',
        category: '食品',
        specification: '大包装',
        unit: '包',
        quantity: 3,
        minStock: 15,
        maxStock: 100,
        costPrice: 6.50,
        salePrice: 12.00,
        warehouse: '主仓库',
        lastUpdated: new Date('2024-01-11').toISOString(),
        supplier: '零食制造商'
      },
      {
        id: 'P008',
        code: 'SKU008',
        name: '牙膏',
        category: '日用品',
        specification: '120g',
        unit: '支',
        quantity: 60,
        minStock: 20,
        maxStock: 200,
        costPrice: 8.50,
        salePrice: 15.00,
        warehouse: '分仓库A',
        lastUpdated: new Date('2024-01-18').toISOString(),
        supplier: '日化用品公司'
      }
    ]
    
    // 初始化一些历史记录
    stockHistory.value = [
      {
        id: 'H001',
        productId: 'P001',
        productName: '可口可乐',
        type: 'inbound',
        quantity: 100,
        price: 2.50,
        operator: '张三',
        date: new Date('2024-01-15').toISOString(),
        remark: '新货入库'
      },
      {
        id: 'H002',
        productId: 'P002',
        productName: '康师傅方便面',
        type: 'outbound',
        quantity: 12,
        reason: '销售',
        operator: '李四',
        date: new Date('2024-01-14').toISOString(),
        remark: '正常销售出库'
      }
    ]
  }

  const persist = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(stockList.value))
    localStorage.setItem(HISTORY_KEY, JSON.stringify(stockHistory.value))
  }
  
  // 计算属性 - 库存统计
  const stockStats = computed(() => {
    const stats = {
      totalProducts: stockList.value.length,
      totalQuantity: 0,
      warningProducts: 0,
      outOfStock: 0,
      totalValue: 0
    }
    
    stockList.value.forEach(item => {
      stats.totalQuantity += item.quantity
      stats.totalValue += item.quantity * item.costPrice
      
      if (item.quantity <= 0) {
        stats.outOfStock++
      } else if (item.quantity <= item.minStock) {
        stats.warningProducts++
      }
    })
    
    return stats
  })
  
  // 获取筛选后的库存数据
  const getFilteredStock = (filters) => {
    return stockList.value.filter(item => {
      // 搜索过滤
      if (filters.search) {
        const searchTerm = filters.search.toLowerCase()
        if (!item.name.toLowerCase().includes(searchTerm) && 
            !item.code.toLowerCase().includes(searchTerm)) {
          return false
        }
      }
      
      // 类别过滤
      if (filters.category && item.category !== filters.category) {
        return false
      }
      
      // 状态过滤
      if (filters.status) {
        const status = getItemStatus(item)
        if (status !== filters.status) {
          return false
        }
      }
      
      // 仓库过滤
      if (filters.warehouse && item.warehouse !== filters.warehouse) {
        return false
      }
      
      return true
    })
  }
  
  // 获取商品状态
  const getItemStatus = (item) => {
    if (item.quantity <= 0) return '缺货'
    if (item.quantity <= item.minStock) return '预警'
    return '正常'
  }
  
  // 入库操作
  const inboundStock = (data) => {
    const product = stockList.value.find(item => item.id === data.productId)
    if (product) {
      // 更新库存数量
      product.quantity += data.quantity
      // 更新成本价（加权平均）
      const totalCost = (product.quantity - data.quantity) * product.costPrice + data.quantity * data.price
      product.costPrice = totalCost / product.quantity
      product.lastUpdated = data.date
      
      // 添加历史记录
      const historyRecord = {
        id: 'H' + Date.now(),
        productId: product.id,
        productName: product.name,
        type: 'inbound',
        quantity: data.quantity,
        price: data.price,
        operator: data.supplier || '系统',
        date: data.date,
        remark: data.remark || '商品入库',
        supplier: data.supplier,
        warehouse: product.warehouse
      }
      stockHistory.value.unshift(historyRecord)
      persist()
    }
  }
  
  // 顾客退货入库（不改变成本价）
  const returnInbound = (data) => {
    const product = stockList.value.find(item => item.id === data.productId)
    if (product) {
      product.quantity += Number(data.quantity || 0)
      product.lastUpdated = data.date

      const historyRecord = {
        id: 'H' + Date.now(),
        productId: product.id,
        productName: product.name,
        type: 'return',
        quantity: Number(data.quantity || 0),
        reason: data.reason || '顾客退货',
        operator: data.operator || '系统',
        date: data.date || new Date().toISOString(),
        remark: data.remark || '顾客退货入库',
        warehouse: product.warehouse
      }
      stockHistory.value.unshift(historyRecord)
      persist()
      return true
    }
    return false
  }

  // 出库操作
  const outboundStock = (data) => {
    const product = stockList.value.find(item => item.id === data.productId)
    if (product && product.quantity >= data.quantity) {
      // 更新库存数量
      product.quantity -= data.quantity
      product.lastUpdated = data.date
      
      // 添加历史记录
      const historyRecord = {
        id: 'H' + Date.now(),
        productId: product.id,
        productName: product.name,
        type: 'outbound',
        quantity: data.quantity,
        reason: data.reason,
        operator: data.operator,
        date: data.date,
        remark: data.remark || '商品出库'
      }
      stockHistory.value.unshift(historyRecord)
      persist()
      return true
    }
    return false
  }
  
  // 盘点操作
  const inventoryStock = (data) => {
    const product = stockList.value.find(item => item.id === data.productId)
    if (product) {
      const originalQuantity = product.quantity
      const difference = data.actualQuantity - originalQuantity
      
      // 更新库存数量
      product.quantity = data.actualQuantity
      product.lastUpdated = data.date
      
      // 添加历史记录
      const historyRecord = {
        id: 'H' + Date.now(),
        productId: product.id,
        productName: product.name,
        type: 'inventory',
        quantity: difference,
        originalQuantity: originalQuantity,
        actualQuantity: data.actualQuantity,
        operator: data.operator,
        date: data.date,
        remark: data.remark || '库存盘点'
      }
      stockHistory.value.unshift(historyRecord)
      persist()
      return { difference, originalQuantity, actualQuantity: data.actualQuantity }
    }
    return null
  }
  
  // 添加新商品
  const addProduct = (productData) => {
    const newProduct = {
      id: 'P' + Date.now(),
      code: productData.code,
      name: productData.name,
      category: productData.category,
      specification: productData.specification,
      unit: productData.unit,
      quantity: productData.quantity || 0,
      minStock: productData.minStock || 0,
      maxStock: productData.maxStock || 1000,
      costPrice: productData.costPrice || 0,
      salePrice: productData.salePrice || 0,
      warehouse: productData.warehouse || '主仓库',
      lastUpdated: new Date().toISOString(),
      supplier: productData.supplier || ''
    }
    
    stockList.value.push(newProduct)
    persist()
    return newProduct
  }
  
  // 更新商品信息
  const updateProduct = (productId, updates) => {
    const productIndex = stockList.value.findIndex(item => item.id === productId)
    if (productIndex !== -1) {
      stockList.value[productIndex] = {
        ...stockList.value[productIndex],
        ...updates,
        lastUpdated: new Date().toISOString()
      }
      persist()
      return stockList.value[productIndex]
    }
    return null
  }
  
  // 删除商品
  const deleteProduct = (productId) => {
    const productIndex = stockList.value.findIndex(item => item.id === productId)
    if (productIndex !== -1) {
      stockList.value.splice(productIndex, 1)
      persist()
      return true
    }
    return false
  }
  
  // 获取库存历史记录
  const getStockHistory = (productId = null, type = null) => {
    let history = stockHistory.value
    
    if (productId) {
      history = history.filter(record => record.productId === productId)
    }
    
    if (type) {
      history = history.filter(record => record.type === type)
    }
    
    return history.sort((a, b) => new Date(b.date) - new Date(a.date))
  }
  
  // 获取预警商品列表
  const getWarningProducts = () => {
    return stockList.value.filter(item => {
      return item.quantity > 0 && item.quantity <= item.minStock
    })
  }
  
  // 获取缺货商品列表
  const getOutOfStockProducts = () => {
    return stockList.value.filter(item => item.quantity <= 0)
  }
  
  // 导出库存数据
  const exportStock = (data = null) => {
    const exportData = data || stockList.value
    const headers = [
      '商品编码', '商品名称', '类别', '规格', '单位', 
      '当前库存', '最低库存', '最高库存', '成本价', '售价', 
      '库存价值', '仓库位置', '状态', '最后更新'
    ]
    
    const csvContent = [
      headers.join(','),
      ...exportData.map(item => [
        item.code,
        item.name,
        item.category,
        item.specification,
        item.unit,
        item.quantity,
        item.minStock,
        item.maxStock,
        item.costPrice.toFixed(2),
        item.salePrice.toFixed(2),
        (item.quantity * item.costPrice).toFixed(2),
        item.warehouse,
        getItemStatus(item),
        new Date(item.lastUpdated).toLocaleDateString('zh-CN')
      ].join(','))
    ].join('\n')
    
    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `库存数据_${new Date().toISOString().split('T')[0]}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    return true
  }
  
  // 批量更新库存
  const batchUpdateStock = (updates) => {
    updates.forEach(update => {
      const product = stockList.value.find(item => item.id === update.productId)
      if (product) {
        Object.assign(product, update.data)
        product.lastUpdated = new Date().toISOString()
      }
    })
    persist()
  }
  
  // 获取库存价值分析
  const getStockValueAnalysis = () => {
    const analysis = {
      totalValue: 0,
      categoryValue: {},
      warehouseValue: {},
      topValueProducts: []
    }
    
    stockList.value.forEach(item => {
      const itemValue = item.quantity * item.costPrice
      analysis.totalValue += itemValue
      
      // 按类别统计
      if (!analysis.categoryValue[item.category]) {
        analysis.categoryValue[item.category] = 0
      }
      analysis.categoryValue[item.category] += itemValue
      
      // 按仓库统计
      if (!analysis.warehouseValue[item.warehouse]) {
        analysis.warehouseValue[item.warehouse] = 0
      }
      analysis.warehouseValue[item.warehouse] += itemValue
    })
    
    // 获取价值最高的商品
    analysis.topValueProducts = stockList.value
      .map(item => ({
        ...item,
        totalValue: item.quantity * item.costPrice
      }))
      .sort((a, b) => b.totalValue - a.totalValue)
      .slice(0, 10)
    
    return analysis
  }
  
  return {
    // 状态
    stockList,
    stockHistory,
    
    // 计算属性
    stockStats,
    
    // 方法
    initializeStock,
    getFilteredStock,
    getItemStatus,
    inboundStock,
    returnInbound,
    outboundStock,
    inventoryStock,
    addProduct,
    updateProduct,
    deleteProduct,
    getStockHistory,
    getWarningProducts,
    getOutOfStockProducts,
    exportStock,
    batchUpdateStock,
    getStockValueAnalysis
  }
})